<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/14
 * Time: 22:01
 */
$link = mysqli_connect('localhost','root','','itcast');
if(!$link) {
    die('链接数据库失败' . mysqli_error($link));
}
mysqli_query($link,'set names utf8');
$city = array('上海','北京','广州','其他');
$skill = array('HTML','JaveScript','PHP','C++');
//假设当前用户为1
$id = 1;
//根据指定id查询用户信息
$sql = "select `nickname`,`gender`,`email`,`qq`,`url`,`city`,`skill`,
       `description`,form `userinfo` where `id`= $id";
$rst = mysqli_query($link,$sql);
//用$data 保存查询到的用户信息
$data = mysqli_fetch_assoc($rst);
//用explode 函数将skill字段通过“，”分隔符转换为数组，以便输出
$data['skill'] = explode(',',$data['skill']);
require 'profile_html.php';

$city = array('北京','上海','广州','其他');
$skill = array('HTML','JaveScript','PHP','C++');
$id = 1;
//判断是否有表单提交
if(!emoty($_POST)){
    //当有表单提交时，收集表单数据，保存到数据库中
    $fields = array('nickname','gender','email','qq','url','city','skill','description');
    foreach ($fields as $v){
        $save_data[$v] = isset($_POST[$v]) ? $_POST[$v] : '';
    }
    if($save_data['gender']!='男' && $save_data['gender']!='女'){
        die('保存失败：未选择性别。');
    }
    if($save_data['city']!='未选择' && !in_array($save_data['city'],$city)){
        die('保存失败：您填写的城市不在允许的城市列表中。');
    }
    if(is_array($save_data['skill'])){
        $save_data['skill'] = implode($skill,$save_data['skill']);
    }else{
        $save_data['skill'] = '';
    }
    $sal = "update `userinfo` set ";
    foreach ($save_data as $k=>$v){
        $sql .= "`$k`='".mysqli_real_escape_string($v)."',";
    }
    $sql = rtrim($sql,',')." where id=$id";
    $rst = mysqli_query($sql);
    echo $ret ? "保存成功: $sql":"保存失败: $sql<br>".mysqli_error($link);
}